package com.yomahub.liteflow.example.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.example.bean.PriceCalcReqVO;
import com.yomahub.liteflow.example.bean.ProductPackVO;
import com.yomahub.liteflow.example.bean.PromotionInfoVO;
import com.yomahub.liteflow.example.enums.CategoryEnum;
import com.yomahub.liteflow.example.enums.OrderChannelEnum;
import com.yomahub.liteflow.example.enums.PromotionTypeEnum;
import com.yomahub.liteflow.example.enums.SkuSourceEnum;
import com.yomahub.liteflow.example.freemarker.dto.Product;
import com.yomahub.liteflow.example.freemarker.service.TemplateService;
import com.yomahub.liteflow.example.slot.PriceContext;
import com.yomahub.liteflow.example.utils.HdfsUtil;
import com.yomahub.liteflow.example.xstream.Blog;
import com.yomahub.liteflow.flow.LiteflowResponse;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PriceExampleController {

    @Resource
    private FlowExecutor flowExecutor;

    @Autowired
    private TemplateService templateService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
        PriceCalcReqVO req = mockReq();
        String json = JSON.toJSONString(req);
        modelMap.put("req", json);
        return "index";
    }

    @RequestMapping("editor")
    public String editor(ModelMap modelMap) {
        PriceCalcReqVO req = mockReq();
        String json = JSON.toJSONString(req);
        modelMap.put("req", json);
        return "editor";
    }

    @RequestMapping("layui")
    public String layui(ModelMap modelMap) {
        PriceCalcReqVO req = mockReq();
        String json = JSON.toJSONString(req);
        modelMap.put("req", json);
        return "layui";
    }

    @GetMapping("xml")
    @ResponseBody
    public String demoXml() {
        String templateContentToXml = templateService.getTemplateContentToXml();
        System.out.println(templateContentToXml);
        return templateContentToXml;
    }

    @GetMapping("xmlfile")
    @ResponseBody
    public String demoXmlfile() {
        String templateContentToXmlFile = templateService.getTemplateContentToXmlFile();
        System.out.println(templateContentToXmlFile);
        return templateContentToXmlFile;
    }

    /**
     * 编辑器保存的是字符串，
     * 使用freemarker模板引擎，(模板采用freemarker文件夹下的test.ftlh)
     * 将dataModal数据填充到模板中
     * 返回完成文件
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "text", method = RequestMethod.POST)
    @ResponseBody
    public String save(@Nullable @RequestBody String data) {
        Product product = new Product();
        product.setTemplateFileName("demo.html");
        product.setName("zjy");
        product.setUrl("www.baidu.com");
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", "wwowowow");
        map.put("latestProduct", product);
        List<String> lists = new ArrayList<>();
        lists.add("aaa");
        lists.add("bbb");
        map.put("listStr", lists);
//        不是数组是可以遍历的集合
//        <#list listStr as i>
//              ${i}
//         </#list>
//        方案一
        map.put("ABC_DEF", JSONObject.toJSONString(lists));
//        直接变量显示${lists}
//      方案二
//        String listStr = lists.toString();
//        直接变量显示${lists}
//        map.put("lists", listStr);
//     方案三: 显示json对象
//        List<Map<String, Object>> listMap = new ArrayList<>();
//        listMap.add(MapUtil.builder(new HashMap<String, Object>()).put("name", "zhao").put("age", 1).build());
////        String listMapStr = listMap.toString(); // list = [{name=zhao, age=1}]
//        String listMapStr = JSONObject.toJSONString(listMap); // list = [{"name":"zhao","age":1}]
//        map.put("listMap", listMapStr);
//        方案四：显示pojo
//        Product product1 = new Product();
//        product1.setName("abc");
//        product1.setUrl("http:baidu.com");
//        product1.setTemplateFileName("template");
////        map.put("pojo", product1);  // pojo = Product(templateFileName=template, url=http:baidu.com, name=abc)
//        map.put("pojo", JSONObject.toJSONString(product1)); // list = {"name":"abc","templateFileName":"template","url":"http:baidu.com"}
        String strs = "'b'";
        map.put("str", strs);
        String content = templateService.getTemplateContentFromString(data, map);
//      字符串模板创建指定文件，如果不存在新建，存在覆盖
//        FileUtil.writeUtf8String(content, "E:\\note\\freemarker-project\\src\\main\\java\\com\\yomahub\\liteflow\\example\\controller\\test.html");
        return content;
    }

    // 浏览器下载
    @RequestMapping(value = "upload", method = RequestMethod.GET)
    @ResponseBody
    public HttpServletResponse upload(HttpServletResponse response) {
        String templateContent = templateService.getTemplateContentFromFile();
        try (StringReader reader = new StringReader(templateContent);
             ServletOutputStream output = response.getOutputStream()) {

            response.reset();
            // 定义输入文件名
            String encode = URLEncoder.encode("zjy.html", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encode);
            // 定义输出类型
//            response.setContentType("bin");
//            response.setContentType("application/x-msdownload");
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(reader, output, Charset.forName("UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    // 下载到本地resources
    @RequestMapping(value = "local", method = RequestMethod.GET)
    @ResponseBody
    public void localDown() {
        try {
            String templateContent = templateService.getTemplateContentFromFile();
            ClassPathResource resource = new ClassPathResource("bak/test.html");
            File file = resource.getFile();
            FileUtil.writeUtf8String(templateContent, file);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody

    public String submit(@Nullable @RequestBody String reqData) {
        try {
            PriceCalcReqVO req = JSON.parseObject(reqData, PriceCalcReqVO.class);
            LiteflowResponse response = flowExecutor.execute2Resp("mainChain", req, PriceContext.class);

            return response.getContextBean(PriceContext.class).getPrintLog();
        } catch (Throwable t) {
            t.printStackTrace();
            return "error";
        }
    }

    private PriceCalcReqVO mockReq() {
        PriceCalcReqVO req = new PriceCalcReqVO();
        req.setOrderNo("SO2020070611120001");
        req.setOversea(false);
        req.setMemberCode("M21152");
        req.setOrderChannel(OrderChannelEnum.APP);
        req.setCouponId(80081L);
        List<ProductPackVO> productPackList = new ArrayList<>();
        req.setProductPackList(productPackList);

        ProductPackVO productPack = new ProductPackVO();
        productPack.setProductId(5001L);
        productPack.setProductCode("PD5001XC");
        productPack.setSkuId(67001441L);
        productPack.setSkuCode("SKU5001XC001");
        productPack.setSkuName("夏季运动女式短裙M");
        productPack.setSkuSource(SkuSourceEnum.RAW);
        productPack.setCategory(CategoryEnum.CLOTHES);
        productPack.setSalePrice(new BigDecimal("139.00"));
        productPack.setCount(2);
        productPack.setPromotionList(ListUtil.toList(
                new PromotionInfoVO(1001L, "PM1001", "夏季满减活动", PromotionTypeEnum.FULL_CUT),
                new PromotionInfoVO(1002L, "PM1002", "夏季满折活动", PromotionTypeEnum.FULL_DISCOUNT)));
        productPackList.add(productPack);

        productPack = new ProductPackVO();
        productPack.setProductId(6001L);
        productPack.setProductCode("PD6001XC");
        productPack.setSkuId(67002334L);
        productPack.setSkuCode("SKU6001XC001");
        productPack.setSkuName("男士迷彩短袜均码");
        productPack.setSkuSource(SkuSourceEnum.RAW);
        productPack.setCategory(CategoryEnum.CLOTHES);
        productPack.setSalePrice(new BigDecimal("59.00"));
        productPack.setCount(3);
        productPack.setPromotionList(ListUtil.toList(
                new PromotionInfoVO(1001L, "PM1001", "夏季满减活动", PromotionTypeEnum.FULL_CUT)));
        productPackList.add(productPack);

        productPack = new ProductPackVO();
        productPack.setProductId(8001L);
        productPack.setProductCode("PD8001XC");
        productPack.setSkuId(87002001L);
        productPack.setSkuCode("SKU8001XC001");
        productPack.setSkuName("纯棉毛巾");
        productPack.setSkuSource(SkuSourceEnum.RAW);
        productPack.setCategory(CategoryEnum.DAILY_USE);
        productPack.setSalePrice(new BigDecimal("28.00"));
        productPack.setCount(5);
        productPack.setPromotionList(ListUtil.toList(
                new PromotionInfoVO(1002L, "PM1002", "夏季满折活动", PromotionTypeEnum.FULL_DISCOUNT)));
        productPackList.add(productPack);

        productPack = new ProductPackVO();
        productPack.setProductId(9001L);
        productPack.setProductCode("PD9001XC");
        productPack.setSkuId(97552001L);
        productPack.setSkuCode("SKU9001XC001");
        productPack.setSkuName("杀菌护手凝胶");
        productPack.setSkuSource(SkuSourceEnum.RAW);
        productPack.setCategory(CategoryEnum.DAILY_USE);
        productPack.setSalePrice(new BigDecimal("30"));
        productPack.setCount(2);
        productPack.setPromotionList(ListUtil.toList(
                new PromotionInfoVO(1003L, "PM1003", "618抢购活动", PromotionTypeEnum.RUSH_BUY)));
        productPackList.add(productPack);

        return req;
    }

    @Autowired
    private HdfsUtil hdfsUtil;

    @GetMapping("downcsv")
    @ResponseBody
    public void downcsv(HttpServletRequest request, HttpServletResponse response) {
        hdfsUtil.downLoadToCsv("data.csv", "/qar/test.csv", response);
    }
    @GetMapping("uploadcsv")
    @ResponseBody
    public void uploadcsv() {
        List<Map<String, String>> list = new ArrayList<>();
        list.add(MapUtil.<String, String>builder().put("rownum", "1").put("name", "zhao").put("age", "20").build());
        list.add(MapUtil.<String, String>builder().put("rownum", "2").put("name", "zhao").put("age", "20").build());
        list.add(MapUtil.<String, String>builder().put("rownum", "3").put("name", "zhao").put("age", "20").build());
        list.add(MapUtil.<String, String>builder().put("rownum", "4").put("name", "zhao").put("age", "20").build());
        list.add(MapUtil.<String, String>builder().put("rownum", "5").put("name", "zhao").put("age", "20").build());
        list.add(MapUtil.<String, String>builder().put("rownum", "6").put("name", "zhao").put("age", "20").build());
        hdfsUtil.writeListMapToCSV("id,name,age", list, "/aaa/test.csv");
    }

    @GetMapping("moveCsv")
    @ResponseBody
    public void moveCsv() {
        hdfsUtil.moveLocalFile(new Path("E:\\tmp\\csv\\fd0e9737e5f6488ab62aad8ff940f243-B1377-20231029-194905.csv"), new Path("/aaa"));
    }


}
